package com.oauth.common.server.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.oauth.common.server.beans.OAuthRequestToken;
import com.oauth.service.members.beans.Member;

public class OAuthRequestUtil {

	public static Long getMemberId(HttpServletRequest pRequest) {
		Member member = getMember(pRequest);
		return member.getMemberId();
	}

	public static Member getMember(HttpServletRequest pRequest) {
		Member member = (Member) pRequest.getAttribute("member");
		return member;
	}

	public static OAuthRequestToken getOAuthTokenFromCookie(
			HttpServletRequest pRequest, String pTokenCookieName,
			String pTokenSecretCookieName) {
		Cookie[] cookies = pRequest.getCookies();

		OAuthRequestToken oauthTokenBean = new OAuthRequestToken();

		for (Cookie cookie : cookies) {
			if (cookie.getName().equalsIgnoreCase(pTokenCookieName)) {
				oauthTokenBean.setToken(cookie.getValue());
			} else if (cookie.getName()
					.equalsIgnoreCase(pTokenSecretCookieName)) {
				oauthTokenBean.setTokenSecret(cookie.getValue());
			}
		}

		if (OAuthStringUtil.isBlank(oauthTokenBean.getToken())
				|| OAuthStringUtil.isBlank(oauthTokenBean.getTokenSecret())) {
			return null;
		} else {
			return oauthTokenBean;
		}
	}

	public static void deleteTokenCookies(HttpServletResponse pResponse,
			String pTokenCookieName, String pTokenSecretCookieName) {
		Cookie tokenCookie = new Cookie(pTokenCookieName, "");
		tokenCookie.setMaxAge(0);

		Cookie tokenSecretCookie = new Cookie(pTokenSecretCookieName, "");
		tokenSecretCookie.setMaxAge(0);

		pResponse.addCookie(tokenCookie);
		pResponse.addCookie(tokenSecretCookie);
	}

	public static void createTokenCookies(HttpServletResponse pResponse,
			OAuthRequestToken pOAuthTokenBean, String pTokenCookieName,
			String pTokenSecretCookieName) {
		pResponse.addCookie(new Cookie(pTokenCookieName, pOAuthTokenBean
				.getToken()));
		pResponse.addCookie(new Cookie(pTokenSecretCookieName, pOAuthTokenBean
				.getTokenSecret()));
	}

}
